import Vue from 'vue'
import Router from 'vue-router'
const login = () => import('../view/login.vue')
const layout = () => import('../view/layout.vue')
const index = () => import('../view/index.vue')
const menu = () => import('../view/menu/index.vue')
const menuAdd = () => import('../view/menu/info.vue')
const role = () => import('../view/role/index.vue')
const admin = () => import('../view/admin/index.vue')
const cate = () => import('../view/category/index.vue')
const specs = () => import('../view/specs/index.vue')
const goods = () => import('../view/goods/index.vue')

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/login',
      name: 'login',
      component: login,
      meta: {
        title: '欢迎登录'
      }
    },
    {
      path: '/index',
      component: layout,
      children: [
        {path: '', component: index, meta: {title: '首页'}},
        {path: 'menu', component: menu, meta: {title: '菜单'}},
        {path: 'menu/add', component: menuAdd, meta: {title: '菜单添加'}},
        {path: 'menu/:id', component: menuAdd, meta: {title: '菜单修改'}},
        {path: 'role', component: role, meta: {title: '角色'}},
        {path: 'admin', component: admin, meta: {title: '管理员'}},
        {path: 'category', component: cate, meta: {title: '商品分类'}},
        {path: 'specs', component: specs, meta: {title: '商品规格'}},
        {path: 'goods', component: goods, meta: {title: '商品管理'}},
      ]
    },
    {
      path: '/',
      redirect: '/index'
    }
  ]
})
router.beforeEach((to, from, next) => {
  document.title = to.meta.title;
  if(to.path === '/login' || to.path === '/index') {
    // 登录页和首页不需要登录，别的都要校验
    next()
  }else {
    // 校验是否登录
    let userInfo = JSON.parse(localStorage.getItem('userInfo'));
    if(userInfo) {
      // 已经登录
      next()
    }else {
      // 没有登录
      next('/login')
    }
  }
})

export default router
